package com.fhz.a2102mvi.utils

import com.fhz.a2102mvi.cons.SERVER_HOST
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**

 */
class RetrofitFactory private constructor(){ private val retrofit: Retrofit
    init {
        retrofit=Retrofit.Builder()
            .baseUrl(SERVER_HOST)
            .addConverterFactory(GsonConverterFactory.create())
//            .addCallAdapterFactory()
            .client(createOkHttpClient())
            .build()
    }

    /**
     * Create OkHttp Client
     */
    private fun createOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
//            .connectTimeout(TIMEOUT,TimeUnit.SECONDS)
//            .readTimeout(TIMEOUT,TimeUnit.SECONDS)
//            .writeTimeout(TIMEOUT,TimeUnit.SECONDS)
            .addInterceptor(createLoggingInterceptor())
//            .addInterceptor(createTokenInterceptor())
//            .addInterceptor(createNormalErrorHttpCodeInterceptor())
            .build()
    }



    /**
     * 创建token拦截器
     */
//    private fun createTokenInterceptor(): Interceptor {
//        return Interceptor{
//            val request = it.request()
//            var response:Response? = null
//            val token = DataStoreUtils.getData(ConstantValue.TOKEN,"")
//            if (!token.isBlank()){
//                val newRequest =  request.newBuilder().addHeader("token",token).build()
//                response=it.proceed(newRequest)
//            }else{
//                response = it.proceed(request)
//            }
//
//            when (response?.code) {
//                /*
//                * 利用LiveDataBus 发送网络状态
//                * */
//                500 ->LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(500)
//                404 -> LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(404)
//                401 ->{
//                    val token = DataStoreUtils.getData(ConstantValue.TOKEN,"")
//                    if (token.isBlank()){
//                        LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(401)
//                    }
//
//                }
//            }
//            if (response?.code==401){
//
//                if (!token.isBlank()){
//                    val newRequest =  request.newBuilder().addHeader("token",token).build()
//                    it.proceed(newRequest)
//                }
//                response!!
//            }else{
//                response!!
//            }
//
//        }
//    }

//    private fun createNormalErrorHttpCodeInterceptor(): Interceptor {
//        return Interceptor {
//            val request = it.request()
//
//            val response = it.proceed(request)
//
//            val code:Int = response.code
//
//            when (code) {
//                /*
//                * 利用LiveDataBus 发送网络状态
//                * */
//                500 ->LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(500)
//                404 -> LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(404)
//                401 ->{
//                    val token = DataStoreUtils.getData(ConstantValue.TOKEN,"")
//                    if (token.isBlank()){
//                        LiveDataBus.with<Int>(ConstantValue.NET_STATE).postValue(401)
//                    }
//
//                }
//            }
//
//            response
//        }
//    }

    /**
     * create logging interceptor and set level
     */
    private fun createLoggingInterceptor(): Interceptor {
        return HttpLoggingInterceptor().apply { level=HttpLoggingInterceptor.Level.BODY }
    }

    companion object{ //伴生对象
        private val instance:RetrofitFactory by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { RetrofitFactory() }
        /**
         * connect read write timeout number
         */
        val TIMEOUT=30L

        fun getRetrofitFactory():RetrofitFactory{
            return instance
        }
    }

    /**
     * create api instance
     */
    fun <T> create(clazz: Class<*>):T{
        return retrofit.create(clazz) as T
    }

}